package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.beans.InvitInfo;
import com.example.chuntiao.cophook.exception.RepeatException;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.ConnectException;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;


public class ScanActivity extends AppCompatActivity {
    private static final String TAG = "ScanActivity";
    ZXingView zXingView;
    boolean flashOpened = false;
    final static int REQ_FOR_CHOOSE_ACTI = 1;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_FOR_CHOOSE_ACTI:
                if (RESULT_OK == resultCode) {
                    String path = null;
                    Uri uri = data.getData();
                    try {
                        final Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                        new AsyncTask<Void, Void, String>() {
                            @Override
                            protected String doInBackground(Void... params) {
                                return QRCodeDecoder.syncDecodeQRCode(bitmap);
                            }

                            @Override
                            protected void onPostExecute(String s) {
                                if (s == null) {
                                    new AlertDialog.Builder(ScanActivity.this)
                                            .setMessage("解析失败")
                                            .setPositiveButton(R.string.yse, null)
                                            .show();
                                    return;
                                }
                                new ReadCodeTask(s).execute();
                            }
                        }.execute();
                    } catch (IOException e) {
                        e.printStackTrace();
                        new AlertDialog.Builder(ScanActivity.this)
                                .setMessage("解析失败")
                                .setPositiveButton(R.string.yse, null)
                                .show();
                    }
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        zXingView = (ZXingView) findViewById(R.id.zbarview);
        zXingView.setDelegate(new QRCodeView.Delegate() {

            @Override
            public void onScanQRCodeSuccess(final String result) {
                vibrate();
                new ReadCodeTask(result).execute();
            }

            @Override
            public void onScanQRCodeOpenCameraError() {

            }
        });


        TextView textOpenLight = (TextView) findViewById(R.id.txt_open_light);
        textOpenLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flashOpened) {
                    zXingView.closeFlashlight();
                    ((TextView) v).setText("开灯");
                    flashOpened = false;
                } else {
                    zXingView.openFlashlight();
                    ((TextView) v).setText("关灯");
                    flashOpened = true;
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_scan, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_from_album:
                Intent intent = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQ_FOR_CHOOSE_ACTI);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        zXingView.startCamera();
        zXingView.startSpotDelay(100);
    }

    @Override
    protected void onStop() {
        zXingView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zXingView.onDestroy();
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }


    class ReadCodeTask extends AsyncTask<Void, Void, Boolean> {

        AlertDialog alertDialog = null;
        ProgressDialog progressDialog = null;
        String result = null;

        public ReadCodeTask(String result) {
            super();
            this.result = result;
        }

        @Override
        protected void onPreExecute() {

            progressDialog = ProgressDialog.show(ScanActivity.this, "稍后", "正在加入组织");
            alertDialog = new AlertDialog.Builder(ScanActivity.this)
                    .setMessage("加入失败，通道已经关闭")
                    .setPositiveButton(R.string.yse, null)
                    .create();

        }

        @Override
        protected Boolean doInBackground(Void... params) {

            InvitInfo info = new Gson().fromJson(result, InvitInfo.class);

            try {
                boolean joined = HttpTool.sendOkHttpJoinOrg(ScanActivity.this, info);
                return joined;
            } catch (RepeatException e) {
                alertDialog.setMessage("用户已经存在");
            } catch (ConnectException e) {
                e.printStackTrace();
                alertDialog.setMessage("网络错误");
            } catch (IOException e) {
                e.printStackTrace();
                alertDialog.setMessage("未知错误");
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            progressDialog.dismiss();
            if (!result) {
                alertDialog.show();
                zXingView.startSpot();
            } else {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

}
